package com.artron.mediaartron.data.net;


import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.data.net.api.CouponApi;
import com.artron.mediaartron.data.net.api.LoginApi;
import com.artron.mediaartron.data.net.api.MaterialLibraryApi;
import com.artron.mediaartron.data.net.api.OrderApi;
import com.artron.mediaartron.data.net.api.OrderAddressApi;
import com.artron.mediaartron.data.net.api.HostApi;
import com.artron.mediaartron.data.net.api.WorksApi;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.artron.mediaartron.data.net.NetConstant.HOST;
import static com.artron.mediaartron.data.net.NetConstant.LOGIN_PATH;
import static com.artron.mediaartron.data.net.NetConstant.MATERIAL_PATH;
import static com.artron.mediaartron.data.net.NetConstant.ORDER_ADDRESS_PATH;
import static com.artron.mediaartron.data.net.NetConstant.ORDER_PATH;
import static com.artron.mediaartron.data.net.NetConstant.WORKS_PATH;


public class RetrofitHelper {

    private static OkHttpClient mOkHttpClient;
    private static Gson mJsonParser;


    static {
        initOkHttpClient();
    }

    /**
     * 初始化OKHttpClient
     * 设置缓存
     * 设置超时时间
     * 设置打印日志
     * 设置UA拦截器
     */
    private static void initOkHttpClient() {

        if (mOkHttpClient == null) {
            synchronized (RetrofitHelper.class) {
                if (mOkHttpClient == null) {
                    //设置Http缓存
                    Cache cache = new Cache(new File(UIUtils.getContext()
                            .getExternalCacheDir(), "HttpCache"), 1024 * 1024 * 100);

                    mOkHttpClient = new OkHttpClient.Builder()
                            .cache(cache)
                            .retryOnConnectionFailure(true)
                            .connectTimeout(60, TimeUnit.SECONDS)
                            .writeTimeout(60, TimeUnit.SECONDS)
                            .readTimeout(60, TimeUnit.SECONDS)
                            .addInterceptor(new UserAgentInterceptor())
                            .build();
                }
            }
        }
    }

    /**
     * 添加UA拦截器
     * B站请求API文档需要加上UA
     */
    static class UserAgentInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
//            Request originalRequest = chain.request();
//            Request requestWithUserAgent = originalRequest.newBuilder()
//                    .removeHeader("User-Agent")
//                    .addHeader("User-Agent", COMMON_UA_STR)
//                    .build();

            CacheControl control = new CacheControl.Builder()
                    .maxAge(120, TimeUnit.SECONDS)
                    .build();

            Request original = chain.request();
            Request build = original.newBuilder()
                    .cacheControl(control)
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(build);
        }
    }

    private static <T> T getRetrofitApi(String url, Class<T> clazz) {
        return new Retrofit.Builder()
                .baseUrl(url)
                .client(mOkHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(buildJsonParser()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(clazz);
    }

    public static Gson buildJsonParser() {
        if (mJsonParser == null) {
            mJsonParser = new GsonBuilder()
                .registerTypeAdapterFactory(new SpecialTypeAdapterFactory())
                .create();
        }

        return mJsonParser;
    }

    public static LoginApi getLoginApi() {
        return getRetrofitApi(LOGIN_PATH, LoginApi.class);
    }

    public static MaterialLibraryApi getMaterialApi() {
        return getRetrofitApi(MATERIAL_PATH, MaterialLibraryApi.class);
    }

    public static OrderAddressApi getOrderAddressApi() {
        return getRetrofitApi(ORDER_ADDRESS_PATH, OrderAddressApi.class);
    }

    public static OrderApi getOrderApi() {
        return getRetrofitApi(ORDER_PATH, OrderApi.class);
    }

    public static HostApi getHostApi() {
        return getRetrofitApi(HOST, HostApi.class);
    }

    public static WorksApi getWorksApi() {
        return getRetrofitApi(WORKS_PATH, WorksApi.class);
    }

    public static <T> void subscript(Observable<T> observable, Action1<T> action) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action, new Action1<Throwable>() {
                    @Override
                        public void call(Throwable throwable) {
                        ToastUtil.show("网络异常");
                        MobclickAgent.reportError(UIUtils.getContext(), throwable);
                    }
                });
    }

    public static CouponApi getCouponApi(){
        return getRetrofitApi(NetConstant.COUPON_PATH,CouponApi.class);
    }
}
